//
//  LKAddShopShowViewController.m
//  Mideleague_Shop
//
//  Created by Zhiwang on 2020/7/15.
//  Copyright © 2020 Zhiwang. All rights reserved.
//

#import "LKAddShopShowViewController.h"
#import "LKShopPictureShowCell.h"
#import "LKShopPictureModel.h"
@interface LKAddShopShowViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,UIScrollViewDelegate>

@property(nonatomic,strong)UICollectionView *collectionView;
@property(nonatomic,strong)UICollectionViewFlowLayout *flowLayout;
@property(nonatomic,strong)UIPageControl *pageControl;
@property(nonatomic,strong)NSMutableArray *dataArray;
@property(nonatomic,strong)LKBaseButton *addBtn;
@property(nonatomic,strong)LKBaseButton *saveBtn;
@property(nonatomic,strong)UIImageView *qrImageView;
@property(nonatomic,strong)LKBaseButton *deleteBtn;
@property(nonatomic,strong)LKBaseLabel *bottomLabel;
//@property(nonatomic,strong)LKBaseButton *saveBtn;
@end

@implementation LKAddShopShowViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"店铺展示图";
    [self createHeaderIntroViewWithTile:@"店铺展示图，请上传1~5张" AndBottomIntro:@"(尺寸：600x600，大小：200KB,格式：JPG、JPEG、PNG)"];
    [self createCollectionUI];
    [self getShopShowImagesDataWithPage];
    // Do any additional setup after loading the view.
}
/// 增加客服二维码头部介绍
-(void)createHeaderIntroViewWithTile:(NSString *)title AndBottomIntro:(NSString *)intro{
    WS(weakSelf)
    LKBaseLabel *topLabel = [LKBaseLabel labelWithFrame:CGRectZero text:title textColor:COLOR_HEX(0x333333) font:[UIFont fontWithName:@"PingFangSC-Regular" size:14] textAlignment:NSTextAlignmentCenter];
    [self.view addSubview:topLabel];
    [topLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_top).offset(NAVIGATION_BAR_HEIGHT + 10);
        make.left.equalTo(self.view.mas_left).offset(20);
    }];
    _bottomLabel = [LKBaseLabel labelWithFrame:CGRectZero text:intro textColor:COLOR_HEX(0x333333) font:[UIFont fontWithName:@"PingFangSC-Regular" size:12] textAlignment:NSTextAlignmentCenter];
    [self.view addSubview:_bottomLabel];
    [_bottomLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(topLabel.mas_bottom).offset(30);
        make.left.equalTo(self.view.mas_left).offset(20);
    }];
//    self.addBtn = [LKBaseButton buttonWithFrame:CGRectMake(0, 0, 64, 24) type:UIButtonTypeCustom title:@"+" titleColor:[UIColor whiteColor] layercorne:30 font:[UIFont fontWithName:@"PingFangSC-Regular" size: 24] backgroudColor:[UIColor redColor] AndActionBlock:^(UIButton * _Nonnull btn) {
//        [weakSelf showAlertChooseVc];
//    }];
//    [self.view addSubview:self.addBtn];
//    [self.addBtn mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.right.equalTo(self.view.mas_right).offset(-20);
//        make.bottom.equalTo(self.view.mas_bottom).offset(-30);
//        make.size.mas_equalTo(CGSizeMake(60, 60));
//    }];
//    self.qrImageView = [[UIImageView alloc] init];
//    self.qrImageView.userInteractionEnabled = YES;
//    [self.qrImageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",ServerlUrl,[NSString judegeIsNullAndTransform:self.qrImageUrl]]] placeholderImage:[UIImage imageNamed:@""]];
//    [self.view addSubview:_qrImageView];
//    [_qrImageView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.right.equalTo(self.view);
//        make.centerY.equalTo(self.view);
//        make.height.mas_equalTo((HEIGHT -NAVIGATION_BAR_HEIGHT)/2);
//
//    }];

//    if (self.qrImageUrl.length != 0) {
//        self.addBtn.hidden = YES;
//    }else{
//        self.qrImageView.hidden = YES;
//    }
}
/**
 创建collectioview的布局
 */
-(void)createCollectionUI{
    WS(weakSelf)
    self.flowLayout = [[UICollectionViewFlowLayout alloc] init];
    self.flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:self.flowLayout];
    [self.view addSubview:self.collectionView];
    self.collectionView.backgroundColor = viewDefualtColor;
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;
        if (@available(iOS 11.0, *)) {
        self.collectionView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        // Fallback on earlier versions
    }
    self.collectionView.pagingEnabled = YES;
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left).offset(0);
        make.top.equalTo(self.bottomLabel.mas_bottom).offset(10);
        make.height.mas_equalTo((HEIGHT - NAVIGATION_BAR_HEIGHT)/2);
        make.width.mas_equalTo(WIDTH);
    }];
    self.pageControl = [[UIPageControl alloc] init];
    _pageControl.pageIndicatorTintColor = [UIColor grayColor];
    _pageControl.currentPageIndicatorTintColor = [UIColor greenColor];
    _pageControl.currentPage = 0;
    [self.view addSubview:self.pageControl];
    [self.pageControl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.collectionView.mas_bottom).offset(-20);
        make.centerX.equalTo(self.view);
        make.left.equalTo(self.view).offset(100);
        make.height.mas_equalTo(30);
    }];
    self.addBtn = [LKBaseButton buttonWithFrame:CGRectMake(0, 0, 64, 24) type:UIButtonTypeCustom title:@"" titleColor:[UIColor whiteColor] layercorne:30 font:[UIFont fontWithName:@"PingFangSC-Regular" size: 24] backgroudColor:[UIColor lightGrayColor] AndActionBlock:^(UIButton * _Nonnull btn) {
        
        [weakSelf showAlertChooseVc];
    }];
    [self.addBtn setImage:[UIImage imageNamed:@"ic_add_photo"] forState:UIControlStateNormal];
    [self.view addSubview:self.addBtn];
    [self.addBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.view.mas_right).offset(-20);
        make.bottom.equalTo(self.collectionView.mas_bottom).offset(-20);
        make.size.mas_equalTo(CGSizeMake(60, 60));
    }];
    self.deleteBtn = [LKBaseButton buttonWithFrame:CGRectMake(0, 0, 64, 24) type:UIButtonTypeCustom title:@"" titleColor:[UIColor whiteColor] layercorne:30 font:[UIFont fontWithName:@"PingFangSC-Regular" size: 24] backgroudColor:[UIColor lightGrayColor] AndActionBlock:^(UIButton * _Nonnull btn) {
        [weakSelf.dataArray removeObjectAtIndex:weakSelf.pageControl.currentPage];
        [weakSelf.collectionView reloadData];
        weakSelf.addBtn.hidden = NO;
        weakSelf.pageControl.numberOfPages = weakSelf.dataArray.count;
        if (weakSelf.dataArray.count == 0) {
            weakSelf.deleteBtn.hidden = YES;
            weakSelf.collectionView.hidden = YES;
            weakSelf.saveBtn.hidden = YES;
        }
    }];
    [self.deleteBtn setImage:[UIImage imageNamed:@"ic_del"] forState:UIControlStateNormal];
    [self.view addSubview:self.deleteBtn];
    [self.deleteBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.collectionView.mas_right).offset(-20);
        make.top.equalTo(self.collectionView.mas_top).offset(20);
        make.size.mas_equalTo(CGSizeMake(60, 60));
    }];
    [self.view bringSubviewToFront:self.deleteBtn];
    [self.view bringSubviewToFront:self.addBtn];
    [self.collectionView bringSubviewToFront:self.pageControl];
    self.saveBtn = [LKBaseButton buttonWithFrame:CGRectMake(0, 0, 64, 24) type:UIButtonTypeCustom title:@"保存" titleColor:[UIColor whiteColor] layercorne:15 font:[UIFont fontWithName:@"PingFangSC-Regular" size: 16] backgroudColor:[UIColor redColor] AndActionBlock:^(UIButton * _Nonnull btn) {
        NSString *img = @"";
        NSString *sort = @"";
        for (NSInteger i = 0; i < weakSelf.dataArray.count; i++) {
            LKShopPictureModel *model = weakSelf.dataArray[i];
            if (i == 0) {
                img = [NSString stringWithFormat:@"%@",model.img];
                sort = [NSString stringWithFormat:@"%ld",i+1];
            }else{
               img = [NSString stringWithFormat:@"%@,%@",img,model.img];
               sort = [NSString stringWithFormat:@"%@,%ld",sort,i+1];
            }
        }
        NSMutableDictionary *param = [[NSMutableDictionary alloc] initWithDictionary:@{@"img":img,@"sort":sort}];
        NSString *sign = [NSString encoingWithDic:param];
        [param setObject:sign forKey:@"sign"];
        [[LKNetDataManager defaultManager] sendRequestMethod:HTTPMethodPOST serverUrl:ServerlUrl apiPath:MyShopShowSaveUrl header:[LKUserInforTool account].token parameters:param progress:^(NSProgress * _Nullable progress) {
            
        } success:^(BOOL isSuccess, id  _Nullable responseObject) {
            if ([responseObject[@"code"] isEqualToString:@"success"]) {
                [weakSelf.navigationController popViewControllerAnimated:YES];
            }else{
                [SVProgressHUD showInfoWithStatus:responseObject[@"msg"]];
            }
        } failure:^(NSString * _Nullable errorMessage) {
            
        }];
    }];
    [self.view addSubview:self.saveBtn];
    [self.saveBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.top.equalTo(self.collectionView.mas_bottom).offset(20);
        make.size.mas_equalTo(CGSizeMake(150, 30));
    }];
    [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header"];
    
    [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"footer"];
    [self.collectionView registerNib:[UINib nibWithNibName:@"LKShopPictureShowCell" bundle:nil] forCellWithReuseIdentifier:@"LKShopPictureShowCell"];
    self.collectionView.showsVerticalScrollIndicator = NO;
    self.collectionView.showsHorizontalScrollIndicator = NO;
    self.collectionView.alwaysBounceHorizontal = YES;
}
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.dataArray.count;

}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    LKShopPictureShowCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"LKShopPictureShowCell" forIndexPath:indexPath];
    cell.model = self.dataArray[indexPath.item];
    return cell;
}
-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    if ([kind isEqual:UICollectionElementKindSectionHeader]) {
        UICollectionReusableView *header = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"header" forIndexPath:indexPath];
        return header;
    }else{
        UICollectionReusableView *footer = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"footer" forIndexPath:indexPath];
        return footer;
    }
}
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    return CGSizeZero;
}
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section{
    return CGSizeZero;
}
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return CGSizeMake(WIDTH, (HEIGHT - NAVIGATION_BAR_HEIGHT)/2);
}
-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 0;
}
-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 0;
}
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    CGFloat pageWidth = self.collectionView.frame.size.width;
    self.pageControl.currentPage = scrollView.contentOffset.x/pageWidth;
}
-(NSMutableArray *)dataArray{
    if (_dataArray == nil) {
        _dataArray = [[NSMutableArray alloc] init];
    }
    return _dataArray;
}
-(void)getShopShowImagesDataWithPage{
    WS(weakSelf)
    NSMutableDictionary *param = [[NSMutableDictionary alloc] initWithDictionary:@{}];
    NSString *sign = [NSString encoingWithDic:param];
    [param setObject:sign forKey:@"sign"];
    [[LKNetDataManager defaultManager] sendRequestMethod:HTTPMethodPOST serverUrl:ServerlUrl apiPath:MyShopShowImagesUrl header:[LKUserInforTool account].token parameters:param progress:^(NSProgress * _Nullable progress) {
        
    } success:^(BOOL isSuccess, id  _Nullable responseObject) {
        if ([responseObject[@"code"] isEqualToString:@"success"]) {
            NSArray *dicArray = responseObject[@"data"];
            for (NSDictionary *dic in dicArray) {
                LKShopPictureModel *model = [LKShopPictureModel modelWithDictionary:dic];
                if (model.img.length != 0) {
                    [self.dataArray addObject:model];
                }else{
                    
                }
            }
            if (weakSelf.dataArray.count == 5) {
                weakSelf.addBtn.hidden = YES;
            }
            weakSelf.pageControl.numberOfPages = self.dataArray.count;
            [self.collectionView reloadData];
        }else{
            [SVProgressHUD showInfoWithStatus:responseObject[@"msg"]];
        }
    } failure:^(NSString * _Nullable errorMessage) {
        
    }];
}
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerControllerInfoKey,id> *)info{
    WS(weakSelf)
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    if ([type isEqualToString:@"public.image"]) {

        UIImage *photo = [info objectForKey:UIImagePickerControllerOriginalImage];
//        row.selectImageV.superview.userInteractionEnabled = NO;
        weakSelf.qrImageView.image = photo;
        [SVProgressHUD showWithStatus:@"图片上传中..."];
        [[LKNetDataManager defaultManager] sendPOSTRequestWithserverUrl:ServerlUrl apiPath:ImageUploadUrl parameters:nil imageArray:@[photo] targetWidth:100 progress:^(NSProgress * _Nullable progress) {
            
                } success:^(BOOL isSuccess, id  _Nullable responseObject) {
                    [SVProgressHUD dismiss];
                    if ([responseObject[@"code"] isEqualToString:@"success"]) {
                        if ([NSString isBlankString:responseObject[@"data"]]) {
                            [SVProgressHUD showInfoWithStatus:@"图片未上传成功，请重新选择"];
                            return ;
                        }
                        LKShopPictureModel *model = [[LKShopPictureModel alloc] init];
                        model.img = weakSelf.qrImageUrl = responseObject[@"data"];
                        [weakSelf.dataArray addObject:model];
                        if (weakSelf.dataArray.count == 5) {
                            weakSelf.addBtn.hidden = YES;
                        }
                        weakSelf.deleteBtn.hidden = NO;
                        weakSelf.collectionView.hidden = NO;
                        weakSelf.saveBtn.hidden = NO;
                        weakSelf.pageControl.numberOfPages = weakSelf.dataArray.count;
                        [weakSelf.collectionView reloadData];
                    }else{
                       [SVProgressHUD showInfoWithStatus:responseObject[@"msg"]];
                    }
            
                } failure:^(NSString * _Nullable error) {
            
                }];

        
    }
    [picker dismissViewControllerAnimated:YES completion:nil];
}

-(void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto infos:(NSArray<NSDictionary *> *)infos{
    WS(weakSelf)
    weakSelf.qrImageView.image = photos[0];
    [SVProgressHUD showWithStatus:@"图片上传中..."];
    [[LKNetDataManager defaultManager] sendPOSTRequestWithserverUrl:ServerlUrl apiPath:ImageUploadUrl parameters:nil imageArray:@[photos[0]] targetWidth:100 progress:^(NSProgress * _Nullable progress) {
        
            } success:^(BOOL isSuccess, id  _Nullable responseObject) {
                [SVProgressHUD dismiss];
                if ([responseObject[@"code"] isEqualToString:@"success"]) {
                    if ([NSString isBlankString:responseObject[@"data"]]) {
                        [SVProgressHUD showInfoWithStatus:@"图片未上传成功，请重新选择"];
                        return ;
                    }
                    LKShopPictureModel *model = [[LKShopPictureModel alloc] init];
                    model.img = weakSelf.qrImageUrl = responseObject[@"data"];
                    [weakSelf.dataArray addObject:model];
                    if (weakSelf.dataArray.count == 5) {
                        weakSelf.addBtn.hidden = YES;
                    }
                    weakSelf.deleteBtn.hidden = NO;
                    weakSelf.collectionView.hidden = NO;
                    weakSelf.saveBtn.hidden = NO;
                    weakSelf.pageControl.numberOfPages = weakSelf.dataArray.count;
                    [weakSelf.collectionView reloadData];
                }else{
                   [SVProgressHUD showInfoWithStatus:responseObject[@"msg"]];
                }
        
            } failure:^(NSString * _Nullable error) {
        
            }];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
